/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.flow.pay;

import com.lxk.oms.order.domain.bo.OmsOrderBo;
import com.lxk.oms.order.domain.vo.OmsOrderVo;
import com.lxk.oms.order.service.IOmsOrderService;
import com.lxk.service.idgenerator.GeneratorType;
import com.lxk.service.idgenerator.IdGeneratorServiceApi;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;

import java.math.BigDecimal;
import java.util.List;

/**
 * 支付订单处理+合单处理
 *
 * @author heyi
 * 2024/10/15
 */
@LiteflowComponent(value = FlowPayOrderNodeConst.GEN_PAY)
@AllArgsConstructor
public class GenPayNode extends NodeComponent {
    private final IOmsOrderService omsOrderService;
    private final IdGeneratorServiceApi generatorServiceApi;

    @Override
    public void process() throws Exception {
        PayContext contextBean = getContextBean(PayContext.class);
        List<OmsOrderVo> omsOrderVoList = contextBean.getOmsOrder();
        PayContext.PayInnerOrder payInnerOrder = contextBean.getPayInnerOrder();
        String outTradeNo = generatorServiceApi.generatorSn(GeneratorType.ORDER_T_P);
        payInnerOrder.setOutTradeNo(outTradeNo);
        // 更新合并订单号和支付方式
        String combineOutTradeNo = generatorServiceApi.generatorSn(GeneratorType.ORDER_MERGE);
        omsOrderVoList.forEach(item -> {
            OmsOrderBo update = new OmsOrderBo();
            update.setId(item.getId());
            update.setPayType(item.getPayType());
            update.setCombineOutTradeNo(combineOutTradeNo);
            update.setOutTradeNo(payInnerOrder.getOutTradeNo());
            omsOrderService.updateByBo(update);
        });
        // 生成合单信息
        BigDecimal totalPrice = omsOrderVoList.stream().map(OmsOrderVo::getActPayPrice).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        if (omsOrderVoList.size() > 1) {
            payInnerOrder.setCombine(true);
        }
        payInnerOrder.setTotalPrice(totalPrice);
        payInnerOrder.setTenantId(contextBean.getTenantId());


    }
}
